import Vue from 'vue'
import Vuex from 'vuex'
import uploadImg from '@/network/uploadImg'
import setGoods from '@/network/setGoods'
import addGoods from '@/network/addGoods'
import delGoods from '@/network/delGoods'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        goods: []
    },
    getters: {
        getGoodsTitle: (state) => state.goods.map(item => item.title),
        getGoodsData: (state) => (index) => state.goods[index].data,
        getGoodsNum: (state) => state.goods.reduce((p, i) => p + i.data.length, 0),
        getGoodsItemNum: (state) => state.goods.map(item => ({ title: item.title, num: item.data.length })),
    },
    mutations: {
        setGoods: (state, pyload) => state.goods = pyload,
        delGoods: (state, {listIndex,dataIndex})=>{
            state.goods[listIndex].data.splice(dataIndex, 1)
        },
        addGoodsItem: (state, {title,index, data})=>{
            state.goods = state.goods.map((item)=>{
                if (item.title == title) {
                    const newItem = [...item.data]
                    data._id = Math.random()
                    newItem.unshift(data)
                    item.data = newItem
                }
                return item
            })
        },
        setGoodsItem: (state, {title,index, data}) => {
            state.goods = state.goods.map((item)=>{
                if (item.title == title) {
                    const newItem = [...item.data]
                    const newData = {...newItem[index], ...data}
                    newItem.splice(index, 1, newData)
                    item.data = newItem
                }
                return item
            })
        }
    },
    actions: {
        async setGoodsServer({commit}, {item, uploadData}){
            const imgInfo = uploadData.img ? await uploadImg(uploadData.img) : null
            if(imgInfo){
                uploadData.img = imgInfo.data.filepath
            }
            await setGoods({id:uploadData.id, data:uploadData})
           commit("setGoodsItem", {...item, data:uploadData})
        },
        addGoodsServer({commit}, payload){
            uploadImg(payload.file).then((res)=>{
                const filepath = res.data.filepath
                const {title, data} = payload
                data.img = filepath
                return addGoods({title, data})
            }).then((res)=>{
                commit('addGoodsItem', payload)
            })
        },
        delGoodsServer({commit}, {listIndex,dataIndex,id}){
            return new Promise((resolve)=>{
                delGoods(id).then((res)=>{
                    commit("delGoods",{listIndex,dataIndex})
                    resolve()
                })
            })
        }
    },
    modules: {
    }
})
